#include  "motor.h"

/**
 * 电机初始化，本项目采用通用定时器2作为pwm输出
 */
void motor_init(void)
{
    GPIO_InitTypeDef GPIO_InitStructure={0};
    TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure={0};
    TIM_OCInitTypeDef   Tim_OCInitStructure={0};

    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);

    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOA,&GPIO_InitStructure);

    TIM_TimeBaseStructure.TIM_Period=100;     //pwm频率为1000hz
    TIM_TimeBaseStructure.TIM_Prescaler=720-1;
    TIM_TimeBaseStructure.TIM_ClockDivision=TIM_CKD_DIV1;
    TIM_TimeBaseStructure.TIM_CounterMode=TIM_CounterMode_Up;
    TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);

    Tim_OCInitStructure.TIM_Pulse=wind_stop;
    Tim_OCInitStructure.TIM_OutputState=TIM_OutputState_Enable;
    Tim_OCInitStructure.TIM_OCMode=TIM_OCMode_PWM1;
    Tim_OCInitStructure.TIM_OCPolarity=TIM_OCPolarity_High;
    TIM_OC1Init(TIM2, &Tim_OCInitStructure);

    // TIM_CtrlPWMOutputs(TIM2, ENABLE);  只在tim1输出时有效
    TIM_OC1PreloadConfig(TIM2, TIM_OCPreload_Disable);
    TIM_ARRPreloadConfig(TIM2, ENABLE);
    TIM_Cmd(TIM2, ENABLE);
}

void set_motor_duty(int duty) {
    TIM_SetCompare1(TIM2, duty);
}

void set_motor_pwm(uint16_t pwm) {
    TIM_SetAutoreload(TIM2,pwm);
}

void set_motor_en(FunctionalState NewState)
{
	TIM_Cmd(TIM2, NewState);
}
